package cn.tjad.tjad2.module.form.views;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.qiandian.android.base.common.bean.CommonBean;

import java.io.File;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import cn.qqtheme.framework.picker.FilePicker;
import cn.tjad.tjad2.BuildConfig;
import cn.tjad.tjad2.R;
import cn.tjad.tjad2.consts.Keys;
import cn.tjad.tjad2.data.bean.FileBean;
import cn.tjad.tjad2.data.bean.FormDetail;
import cn.tjad.tjad2.module.common.dialog.OnDialogClickListener;
import cn.tjad.tjad2.module.common.dialog.TjDialogFragment;
import cn.tjad.tjad2.net.http.ResponseObserver;
import cn.tjad.tjad2.net.http.RetrofitManager;
import cn.tjad.tjad2.route.PageId;
import cn.tjad.tjad2.utils.AppUtils;
import cn.tjad.tjad2.utils.ProgressDialogUtils;
import cn.tjad.tjad2.utils.RouteUtils;
import cn.tjad.tjad2.utils.RxUtils;
import cn.tjad.tjad2.utils.Tools;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class AttachmentSelectWidget extends FormBaseLayout implements View.OnClickListener {

    private TextView addButton;
    private List<FileBean> fileList;

    public AttachmentSelectWidget(Context context) {
        super(context);
    }

    public AttachmentSelectWidget(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init() {
        setOrientation(VERTICAL);
        setGravity(Gravity.RIGHT);
        addButton();
        fileList = new ArrayList<>();
        this.setOnClickListener(this);
    }

    private void addButton() {
        if (addButton == null) {
            addButton = new TextView(getContext());
            addButton.setGravity(Gravity.CENTER_VERTICAL);
            addButton.setText("新增");
            addButton.setTextSize(14);
            addButton.setTextColor(AppUtils.getColor(R.color.blue));
        }
        if (addButton.getParent() == null) {
//            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//            lp.gravity = Gravity.RIGHT;
            this.addView(addButton);
        }
    }

    @Override
    public void setFormStepDetail(FormDetail.FormStepDetail formStepDetail) {
        super.setFormStepDetail(formStepDetail);
        setFileList(formStepDetail.fileList);
    }

    private void setFileList(List<FileBean> files) {
        Log.d("yhb", "setFileList " + this.fileList);
        this.fileList.clear();
        if (files != null) {
            this.fileList.addAll(files);
        }
        if (this.fileList != null && this.fileList.size() > 0) {
            Iterator<FileBean> iterator = this.fileList.iterator();
            while (iterator.hasNext()) {
                addAttachmentView(iterator.next());
            }
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (enabled) {
            addButton();
        } else {
            this.removeView(addButton);
        }
        showDeleteButton(enabled);
    }

    @Override
    public void onClick(View v) {
        new TjDialogFragment.Builder(getContext())
                .setTitle("添加附件")
                .setMessage("添加本地文件还是在线文件？")
                .setPositiveButton("本地上传", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialog, int which) {
                        showFilePicker();
                        return true;
                    }
                })
                .setNegativeButton("在线文件", new OnDialogClickListener() {
                    @Override
                    public boolean onClick(Dialog dialog, int which) {
                        showOnlineFilePicker();
                        return true;
                    }
                }).show(((AppCompatActivity)getContext()).getSupportFragmentManager());
    }

    private void showOnlineFilePicker() {
        RouteUtils.toPageForResult((Activity) getContext(), PageId.FILE_SELECT, null, 1001);
    }

    private void showFilePicker() {
        FilePicker filePicker = new FilePicker((Activity) getContext(), FilePicker.FILE);
        filePicker.setRootPath(Environment.getExternalStorageDirectory().getPath());
        filePicker.setOnFilePickListener(new FilePicker.OnFilePickListener() {
            @Override
            public void onFilePicked(String currentPath) {
                uploadFile(currentPath);
            }
        });
        filePicker.show();
    }

    private void uploadFile(String filePath) {
        ProgressDialogUtils.show(getContext(), "正在上传附件...");
        File file = new File(filePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody body = new MultipartBody.Builder()
                .addFormDataPart("mine", "true")
                .addFormDataPart("file", URLEncoder.encode(file.getName()), requestBody)
                .build();
        RetrofitManager.getInstance()
                .getApiService()
                .uploadFile(Tools.getProjectId(), body)
                .compose(RxUtils.networkTransformer())
                .subscribe(new ResponseObserver<FileBean>(null) {
                    @Override
                    public void onSuccess(CommonBean<FileBean> t) {
                        fileList.add(t.result);
                        addAttachmentView(t.result);
                        ProgressDialogUtils.dismiss();
                    }

                    @Override
                    public void onFailed(String message) {
                        ProgressDialogUtils.dismiss();
                        Tools.showToast(message);
                    }
                });
    }

    private void addAttachmentView(FileBean fileBean) {
        if (fileBean == null) {
            return;
        }
        View attachView = inflate(getContext(), R.layout.attachment_item, null);
        ImageView iconView = attachView.findViewById(R.id.attachment_item_icon);
        TextView fileNameTV = attachView.findViewById(R.id.attachment_item_file_name);
        ImageView deleteIcon = attachView.findViewById(R.id.attachment_item_delete);
        iconView.setImageResource(Tools.getFileSmallIcon(Tools.getFileSubfix(fileBean.name)));
        fileNameTV.setText(URLDecoder.decode(fileBean.name));
        deleteIcon.setTag(attachView);
        deleteIcon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                fileList.remove(fileBean);
                View attachView = (View) v.getTag();
                removeView(attachView);
                notifyFileChanged();
            }
        });
        if (isEnabled()) {
            deleteIcon.setVisibility(VISIBLE);
        } else {
            deleteIcon.setVisibility(GONE);
        }
        this.addView(attachView);
        notifyFileChanged();
    }

    private void notifyFileChanged() {
        String value = getValue();
        if (formStepDetail != null) {
            formStepDetail.value = value;
        }
        if (onEditListener != null) {
            onEditListener.onEdit(formStepDetail.detail.id, value);
        }
        if (BuildConfig.DEBUG) {
            Log.d("TJAD", "附件列表：" + value);
        }
    }

    private void showDeleteButton(boolean show) {
        if (getChildCount() > 0) {
            for (int i = 0; i < getChildCount(); i++) {
                View itemView = getChildAt(i);
                View deleteButton = itemView.findViewById(R.id.attachment_item_delete);
                if (deleteButton != null) {
                    if (show) {
                        deleteButton.setVisibility(VISIBLE);
                    } else {
                        deleteButton.setVisibility(GONE);
                    }
                }
            }
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1001 && resultCode == Activity.RESULT_OK) {
            FileBean selectFile = (FileBean) data.getSerializableExtra(Keys.FILE);
            if (selectFile != null) {
                fileList.add(selectFile);
                addAttachmentView(selectFile);
            }
        }
    }

    @Override
    public String getValue() {
        String value = "";
        if (fileList != null && fileList.size() > 0) {
            for (int i = 0; i < fileList.size(); i++) {
                FileBean fileBean = fileList.get(i);
                value += fileBean.id;
                if (i < fileList.size() - 1) {
                    value += ",";
                }
            }
        }
        return value;
    }
}
